<!-- <script lang="tsx">
import { defineComponent, onMounted, reactive, ref, } from "vue";
import { useRouter, useRoute } from "vue-router";
import backImg from '@img/back.png';
import { UploadFilled } from '@element-plus/icons-vue';
import request from "@/utils/api";
import { ElMessage } from 'element-plus';
import MyFirstSurvey from './components/MyFirstSurvey.vue'

export default defineComponent({
  name: "createPage",
  components: {
    UploadFilled
  },
  setup(_, { }) {
    const router = useRouter();
    const route = useRoute();

    let pathName = window.sessionStorage.getItem('userRole');

    let isReview = pathName == '/review';

    const options = [
      {
        value: '江苏',
        label: '江苏',
        children: [
          {
            value: '南京',
            label: '南京',
          },
          {
            value: '徐州',
            label: '徐州',
          }
        ]
      }
    ]
    const state = reactive({
      formLabelAlign: {
        title: "",
        address: [],
        userName: "",
        fileData: []
      },

    })


    if(route.query.item){
      let routerInfo =  JSON.parse(route.query?.item)
      state.formLabelAlign.title = routerInfo.title
      state.formLabelAlign.address = routerInfo.location.split(',')
      state.formLabelAlign.userName = routerInfo.author
      state.formLabelAlign.fileData = [{
        url:routerInfo.author,
        name:routerInfo.fileName
      }]
    }

    const onFileData = async (item, status) => {
      console.log(item, item.raw)

      let fileData = new FormData()
      if (item.status === "ready") {
        fileData.append('file', item.raw);

        let resp = await request.post('/admin-api/mdm/event-item/upload', fileData,
            {
              headers: {
                'Content-Type': "multipart/form-data"
              }
            }

        );
        state.formLabelAlign.fileData = [{
          url:resp.data,
          name:item.name
        }]

      }

    }

    const surveyRef =  ref();  //名字随意

    const removeFile = (file) => {
      console.log(file)
    }
    const saveBtn = async () => {
      surveyRef.value.test()
      return
      let eventId = route.query.eventId
      let data = {
        eventId,
        title: state.formLabelAlign.title,
        location: state.formLabelAlign.address.join(','),
        author: state.formLabelAlign.userName,
        file: state.formLabelAlign.fileData[0].url,
        status:0
      }
      let isEdit = 'id' in route.query;
      if(isEdit){
        data['id'] = route.query.id;
      }

      try {
        let apiName = isEdit ? 'admin-api/mdm/event-item/update' : 'admin-api/mdm/event-item/create'
        let resp = await request[isEdit?'put':'post'](apiName, data)
        ElMessage.success('操作成功')
        setTimeout(()=>{
          router.back()
        },1200)
      } catch {

      }
    }

    // const data = {"age":"2"}
    const eventId = route.query.eventId

    // 返回渲染函数
    return () => (
        <>
          <div class='h-[64px] w-full p-[0_20px] flex items-center justify-between border-b-(1px solid #e5e5e5)'>
            <div class='flex items-center cursor-pointer' onClick={() => router.back()}>
              <img src={backImg} class='w-[36px] h-[36px] mr-[5px]' />
              <h3 class='text-(18px #000)'>创建新提交/编辑提交</h3>
            </div>
            {
                !isReview && <div class='p-[6px_10px] text-(14px #FFF) bg-[#2A82E4] rounded-[10px] cursor-pointer' onClick={() => saveBtn()}>保存并提交</div>
            }
          </div>

          <div class='w-[960px] m-auto mt-[16px] border-(1px solid #e5e5e5) p-[20px] relative'>
            <div class='absolute inset-0 z-1' v-show={isReview}></div>
            <h2 class='text-16px'>征集表单</h2>
            <MyFirstSurvey event-id={eventId} ref={surveyRef} />
          </div>
        </>
    )
  }
})

</script> -->


<script lang="tsx">
import { defineComponent, onMounted, reactive, ref, } from "vue";
import { useRouter, useRoute } from "vue-router";
import backImg from '@img/back.png';
import { UploadFilled } from '@element-plus/icons-vue';
import request from "@/utils/api";
import { ElMessage, ElMessageBox } from 'element-plus';
import MyFirstSurvey from './components/MyFirstSurvey.vue'

export default defineComponent({
  name: "createPage",
  components: {
    UploadFilled
  },
  setup(_, { }) {
    const router = useRouter();
    const route = useRoute();

    let pathName = window.sessionStorage.getItem('userRole');

    // let name = window.sessionStorage.getItem('name')
    //
    // const checkLogin = async () => {
    //   let r = await request.get('admin-api/system/user/profile/get', {});
    //   console.log('code:' + r.code)
    //   if (r.code != 200) {
    //     router.push('/login')
    //   }
    // }
    //
    // checkLogin()

    let isReview = pathName == '/review';

    const options = [
      {
        value: '江苏',
        label: '江苏',
        children: [
          {
            value: '南京',
            label: '南京',
          },
          {
            value: '徐州',
            label: '徐州',
          }
        ]
      }
    ]
    const state = reactive({
      formLabelAlign: {
        title: "",
        address: [],
        userName: "",
        fileData: []
      }
    })

    if (route.query.item) {
      let routerInfo = JSON.parse(route.query?.item)
      state.formLabelAlign.title = routerInfo.title
      state.formLabelAlign.address = !routerInfo.location ? '' : routerInfo.location.split(',')
      state.formLabelAlign.userName = routerInfo.author
      state.formLabelAlign.fileData = [{
        url: routerInfo.author,
        name: routerInfo.fileName
      }]
    }


    const onFileData = async (item, status) => {
      console.log(item, item.raw)

      let fileData = new FormData()
      if (item.status === "ready") {
        fileData.append('file', item.raw);

        let resp = await request.post('/admin-api/mdm/event-item/upload', fileData,
          {
            headers: {
              'Content-Type': "multipart/form-data"
            }
          }

        );
        state.formLabelAlign.fileData = [{
          url: resp.data,
          name: item.name
        }]

      }

    }


    const removeFile = (file) => {
      console.log(file)
    }

    const downFileFn = ({ fileName, data, type }: any) => {
            var binaryData = [];
            binaryData.push(data);
            let eLink = document.createElement("a");
            eLink.download = fileName;
            eLink.style.display = "none";

            let blob = new Blob(binaryData, {
                type
            });
            eLink.href = URL.createObjectURL(blob);
            document.body.appendChild(eLink);
            eLink.click();
            document.body.removeChild(eLink);
        }

        const downFile = async (item) => {
            // let resp = await request.downFile(`admin-api/mdm/event-item/export-excel?id=${item.id}`);
          let resp = await request.downFile(`admin-api/mdm/event-item/download?id=${item.id}`);
            downFileFn({
                fileName:'问卷数据.xls',
                data:resp, 
                type:resp.type
            })
        }

    const surveyRef =  ref()
    const saveBtn = async () => {
      //下载结果
      if(isReview){
        let routerInfo = JSON.parse(route.query?.item)
        downFile(routerInfo)
        return
      }
      ElMessageBox.confirm(
        '请确认是否提交答卷，提交后不可修改！',
        '确认提交',
        {
          confirmButtonText: '确认提交',
          cancelButtonText: '继续修改',
          type: 'warning',
        }
      )
        .then(async () => {
          surveyRef.value.test()
          return

          let eventId = route.query.eventId
          let data = {
            eventId,
            title: state.formLabelAlign.title,
            location: state.formLabelAlign.address.join(','),
            author: state.formLabelAlign.userName,
            // file: state.formLabelAlign.fileData[0].url,
            status: 0
          }
          //编辑
          let isEdit = 'id' in route.query;
          if (isEdit) {
            data['id'] = route.query.id;
          }

          try {
            let apiName = isEdit ? 'admin-api/mdm/event-item/update' : 'admin-api/mdm/event-item/create'
            let resp = await request[isEdit ? 'put' : 'post'](apiName, data)

            ElMessageBox.confirm(
              '您的提交将帮助我们更好的服务！',
              '感谢反馈！',
              {
                confirmButtonText: '返回主页',
                showCancelButton:false,
                type: 'success',
              }
            )
              .then(async () => {
                  router.replace('/fillList')
              })

          } catch {

          }
        })



    }

    // 返回渲染函数
    return () => (
      <>
        <div class='h-[64px] w-full p-[0_20px] flex items-center justify-between border-b-(1px solid #e5e5e5)'>
          <div class='flex items-center cursor-pointer' onClick={() => router.back()}>
            <img src={backImg} class='w-[36px] h-[36px] mr-[5px]' />
            <h3 class='text-(18px #000)'>{isReview ? '查看主题详情' : '创建新提交/编辑提交'}</h3>
          </div>
          {
             <div style="display:none;" class='p-[6px_10px] text-(14px #FFF) bg-[#2A82E4] rounded-[10px] cursor-pointer' onClick={() => saveBtn()}>{isReview ? '下载结果' : '保存并提交'}</div>
          }
        </div>


        <div class='w-[960px] m-auto mt-[16px] border-(1px solid #e5e5e5) p-[20px] relative'>
          <div class='absolute inset-0 z-1' v-show={isReview}></div>
          <h2 class='text-16px'>征集表单</h2>

          <MyFirstSurvey ref={surveyRef}/>

        </div>


        {/* <div class='w-[960px] m-auto mt-[16px] border-(1px solid #e5e5e5) p-[20px] relative'>
                    <div class='absolute inset-0 z-1' v-show={isReview}></div>
                    <h2 class='text-16px'>征集文件</h2>

                    <el-upload
                        class="upload-demo mt-[30px]"
                        drag
                        auto-upload={false}
                        multiple={false}
                        limit={1}
                        show-file-list={true}
                        v-model:file-list={state.formLabelAlign.fileData}
                        onChange={onFileData}
                        onRemove={removeFile}
                    >
                        <el-icon class="el-icon--upload w-full h-full" ><UploadFilled class='w-full! h-full!' /></el-icon>
                        <div class="el-upload__text">
                            <em class=' text-#999!'>拖拽文件上传</em>
                        </div>
                    </el-upload>
                </div> */}
      </>
    )
  }
})

</script>